package com.markby.fscm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.markby.fscm.common.exception.SSCMException;
import com.markby.fscm.constant.Constants;
import com.markby.fscm.cryptogram.uitls.RSAUtils;
import com.markby.fscm.cryptogram.uitls.SM2Utils;
import com.markby.fscm.domain.KeyStore;
import com.markby.fscm.domain.form.KeyFrom;
import com.markby.fscm.service.KeyStoreService;
import com.markby.fscm.mapper.KeyStoreMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.security.KeyPair;
import java.util.Objects;

/**
 * @author baoyu
 * @description 针对表【key_store】的数据库操作Service实现
 * @createDate 2024-08-12 21:09:06
 */
@Service
@Slf4j
public class KeyStoreServiceImpl extends ServiceImpl<KeyStoreMapper, KeyStore>
        implements KeyStoreService {

    @Override
    public void generateKey(KeyFrom keyFrom) {
        if (keyFrom == null) {
            return;
        }
        KeyPair keyPair;
        if (Objects.equals(keyFrom.getType(), Constants.SM2)) {
            try {
                keyPair = SM2Utils.generateKeyPair();
            } catch (Exception e) {
                log.error("SM2 key generation failed", e);
                throw new SSCMException("SM2 key generation failed", 204);
            }
        } else if (Objects.equals(keyFrom.getType(), Constants.RSA)) {
            try {
                keyPair = RSAUtils.generateKeyPair(2048);
            } catch (Exception e) {
                log.error("RSA key generation failed", e);
                throw new SSCMException("RSA key generation failed", 204);
            }
        } else {
            log.error("Unsupported key type");
            throw new SSCMException("Unsupported key type", 204);
        }
    }
}




